//
//  HJCAjustNumButton.m
//  HJCAdjustButtonTest
//
//  Created by HJaycee on 15/6/4.
//  Copyright (c) 2015年 HJaycee. All rights reserved.
//

#import "HJCAjustNumButton.h"

#define kMaxNumber 99

@interface HJCAjustNumButton ()<UITextFieldDelegate>
{
    UIButton *_decreaseBtn;
    UIButton *_increaseBtn;
    UITextField *_textField;
    UIView *_oneLine;
    UIView *_twoLine;
    NSTimer *_timer;
}

@end

@implementation HJCAjustNumButton



-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupViews];
 

    }return self;
}


- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
   //    [self commonSetup];
}

- (void)setLineColor:(UIColor *)lineColor{
    _lineColor = lineColor;
    
    self.layer.borderColor = [lineColor CGColor];
    _oneLine.backgroundColor = lineColor;
    _twoLine.backgroundColor = lineColor;
}

- (void)setCurrentNum:(NSString *)currentNum{
    _textField.text = currentNum;
    [self adjustBtnEnable:[currentNum integerValue]];
}

- (NSString *)currentNum{
    return _textField.text;
}



- (void)setupViews{
    
    UIColor *lineColor = [UIColor colorWithRed:150/255.0 green:150/255.0 blue:150/255.0 alpha:1.0];
    
//    self.frame = CGRectMake(0, 0, 110, 30);
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = 2;
    self.clipsToBounds = YES;
    self.layer.borderWidth = 0.5;
    self.layer.borderColor = [lineColor CGColor];
    
    _oneLine = [[UIView alloc] init];
    _oneLine.backgroundColor = lineColor;
    [self addSubview:_oneLine];
    
    _twoLine = [[UIView alloc] init];
    _twoLine.backgroundColor = lineColor;
    [self addSubview:_twoLine];
    
    _decreaseBtn = [[UIButton alloc] init];
    [self setupButton:_decreaseBtn normalImage:@"decrease@2x" HighlightImage:@"decrease2@2x"];
    [self addSubview:_decreaseBtn];
    
    _increaseBtn = [[UIButton alloc] init];
    [self setupButton:_increaseBtn normalImage:@"increase@2x" HighlightImage:@"increase2@2x"];
    [self addSubview:_increaseBtn];
    
    _textField = [[UITextField alloc] init];
#warning xhq
    _textField.userInteractionEnabled = NO;
    _textField.text =  @"1";
    
    
    
    _textField.delegate =self;
    _textField.keyboardType = UIKeyboardTypeNumberPad;
    _textField.textAlignment = NSTextAlignmentCenter;
    _textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _textField.font = kMainFont(15);//    _textField.text = @"1";
    [self addSubview:_textField];
    UIButton *customView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth , kScreenHeight -216)];
    [customView addTarget:self action:@selector(justSJP) forControlEvents:UIControlEventTouchDown];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight -216 - 40, kScreenWidth, 40)];
    view.backgroundColor = [UIColor lightGrayColor];
    [customView addSubview:view];
    
    
    UIButton *btn =[UIButton buttonWithType:0];
    [btn setTitle:@"完成" forState:UIControlStateNormal];
    [view addSubview:btn];
    btn.frame =CGRectMake(kScreenWidth -70,  0, 60, 40);
    [btn addTarget:self action:@selector(sjp) forControlEvents:UIControlEventTouchUpInside];
//    customView.backgroundColor = [UIColor lightGrayColor];
    _textField.inputAccessoryView = customView;
    
    
//    ZHPickView initPickviewWithView: isHaveNavControler:(BOOL)isHaveNavControler;

}



-(void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat viewH = self.frame.size.height;
    CGFloat viewW = self.frame.size.width;
    
    _oneLine.frame = CGRectMake(viewH, 0, 0.5, viewH);
    _decreaseBtn.frame = CGRectMake(0, 0, viewH, viewH);
    _twoLine.frame = CGRectMake(viewW - viewH, 0, 0.5, viewH);
    _increaseBtn.frame = CGRectMake(viewW - viewH, 0, viewH, viewH);
    _textField.frame = CGRectMake(viewH, 0, viewW - viewH * 2, viewH);

}

//- (void)commonSetup{
//    CGFloat viewH = self.frame.size.height;
//    CGFloat viewW = self.frame.size.width;
//    
//    _oneLine.frame = CGRectMake(viewH, 0, 1, viewH);
//    _decreaseBtn.frame = CGRectMake(0, 0, viewH, viewH);
//    _twoLine.frame = CGRectMake(viewW - viewH, 0, 1, viewH);
//    _increaseBtn.frame = CGRectMake(viewW - viewH, 0, viewH, viewH);
//    _textField.frame = CGRectMake(viewH, 0, viewW - viewH * 2, viewH);
//}

- (void)setupButton:(UIButton *)btn normalImage:(NSString *)norImage HighlightImage:(NSString *)highImage{
    [btn setImage:[self readImageFromBundle:norImage] forState:UIControlStateNormal];
    [btn setImage:[self readImageFromBundle:highImage] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(btnTouchDown:) forControlEvents:UIControlEventTouchDown];
    [btn addTarget:self action:@selector(btnTouchUp:) forControlEvents:UIControlEventTouchUpOutside|UIControlEventTouchUpInside|UIControlEventTouchCancel];
}

- (void)btnTouchDown:(UIButton *)btn{
    //手按下，数字修改
    [_textField resignFirstResponder];
    
    if (btn == _increaseBtn) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(increase) userInfo:nil repeats:YES];
    } else {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(decrease) userInfo:nil repeats:YES];
    }
    [_timer fire];
}

- (void)btnTouchUp:(UIButton *)btn{
    //手松开，发送请求
    
    [self cleanTimer];
    [self.delegate ajustNumButton:self didChangeNub:self.currentNum];
}

- (void)increase{
    if (_textField.text.length == 0) {
        _textField.text = @"1";
    }
  
    int newNum = [_textField.text intValue] + 1;
   
    if (newNum <kMaxNumber +1) {


        _textField.text = [NSString stringWithFormat:@"%i", newNum];
        if (self.callBack) {
            self.callBack(_textField.text);
            
        }
        

    }else{
         NSLog(@"num can not more than maxNumer");
        _textField.text =[NSString stringWithFormat:@"%d",kMaxNumber];
    }
    /**
     *  这个方法满足加减按扭的显示状态
     */
    [self adjustBtnEnable:newNum];
}



- (void)decrease{
    if (_textField.text.length == 0) {
        _textField.text = @"1";
    }
    int newNum = [_textField.text intValue] -1;
     [self adjustBtnEnable:newNum];
    if (newNum > 0) {
       
        _textField.text = [NSString stringWithFormat:@"%i", newNum];
        
        if (self.callBack) {
            self.callBack(_textField.text);

        }
        
        
        
    } else {
        NSLog(@"num can not less than 1");
        
        //不然会崩溃,因为在别的地方要把self 删掉了
        [_timer invalidate];
        
        if (self.to0callBack) {
            self.to0callBack();
        }
    }
}

- (UIImage *)readImageFromBundle:(NSString *)imageName{
    NSString *bundlePath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"HJCAdjustNumButton.bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    UIImage *(^getBundleImage)(NSString *) = ^(NSString *n) {
        return [UIImage imageWithContentsOfFile:[bundle pathForResource:n ofType:@"png"]];
    };
    UIImage *myImg = getBundleImage(imageName);
    return myImg;
}

- (void)dealloc{
    [self cleanTimer];
}

- (void)cleanTimer{
    if (_timer.isValid) {
        [_timer invalidate];
        _timer = nil;
    }
}

-(void)adjustBtnEnable:(NSInteger)newNum
{
//    if (newNum ==0) {
//        
//    }
//    if (newNum==1) {
//        _increaseBtn.enabled = YES;
//        _decreaseBtn.enabled =NO;
//    }
//    else if(newNum>1&&newNum <kMaxNumber)
//    {
//        _increaseBtn.enabled = YES;
//        _decreaseBtn.enabled =YES;
//    }
//    else if(newNum ==kMaxNumber)
//    {
//        _increaseBtn.enabled = NO;
//        _decreaseBtn.enabled =YES;
//    }
}


//-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//    if ([textField.text intValue] >10) {
//        textField.text =@"10";
//        return NO;
//    }
//    else if([textField.text intValue] ==0)
//    {
//        textField.text =@"1";
//        return NO;
//    }
//    return YES;
//
//}
//
//
//
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.delegate ajustNumButtonDidBecomeFirstRespond:self];
    
}


-(void)justSJP{
     [_textField resignFirstResponder];
}

-(void)sjp
{
    if (_textField.text.length==0 ||[_textField.text intValue]==0) {
        _textField.text =@"1";
    }
    else if([_textField.text intValue]>kMaxNumber)
    {
        _textField.text =[NSString stringWithFormat:@"%d",kMaxNumber];
    }
    [self adjustBtnEnable:[_textField.text intValue]];
    [_textField resignFirstResponder];

    [self.delegate ajustNumButton:self didChangeNub:self.currentNum];
}



-(void)setNumber:(NSString *)number
{
    _number = number;
      _textField.text = self.number;
    
}
@end
